<template>
  <div class="task">
    <div v-if="showTask">
      <div class="module-detail-header">
        <el-breadcrumb separator-class="el-icon-arrow-right" class="f-left">
          <el-breadcrumb-item @click.native="back" class="cursor-p">考试列表</el-breadcrumb-item>
          <el-breadcrumb-item>
            <span>任务列表</span>
            <span class="text-danger">({{data.title}})</span>
          </el-breadcrumb-item>
        </el-breadcrumb>
        <el-button class="f-right" type="danger" size="small" @click="openDialog">新增任务</el-button>
      </div>
      <el-table
        stripe
        ref="multipleTable"
        :data="taskList"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column
          v-for="(data,index) in taskOpts"
          :key="index"
          :prop="data.field"
          :label="data.th"
          :formatter="data.format"
          align="center"
          :show-overflow-tooltip="true"
          :width="data.width"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handlePaper(scope.row)">试卷</el-button>
            <el-button type="text" size="mini" @click="openDel(scope.row)">删除</el-button>
            <el-popover placement="right" class="qrcode" width="180" trigger="click">
              <img :src="qrcodeSrc" width="160" alt />
              <el-button
                slot="reference"
                type="text"
                size="mini"
                @click="handleQrcode(scope.row)"
              >&nbsp;&nbsp;&nbsp;二维码</el-button>
            </el-popover>
            <el-popover placement="right" class="qrcode" width="180" trigger="click">
              <img :src="scoreCodeSrc" width="160" alt />
              <el-button
                slot="reference"
                type="text"
                size="mini"
                @click="handleScoreCode(scope.row)"
              >&nbsp;&nbsp;&nbsp;成绩</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="任务编辑" width="40%" :visible.sync="dialogVisible">
        <div class="over-hid">
          <!-- {{taskObj}} -->
          <v-input sm="24" label="任务名称">
            <el-input size="small" v-model="taskObj.title" placeholder="考试名称"></el-input>
          </v-input>
          <v-input sm="24" label="考试描述">
            <el-input size="small" type="textarea" v-model="taskObj.description" placeholder="考试描述"></el-input>
          </v-input>
          <v-input sm="24" label="开始时间">
            <el-date-picker
              size="small"
              v-model="taskObj.begin"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </v-input>
          <v-input sm="24" label="结束时间">
            <el-date-picker
              size="small"
              v-model="taskObj.end"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </v-input>
          <v-input sm="24" label="考试时长">
            <el-input
              type="number"
              min="1"
              v-model.number="taskObj.duration"
              placeholder="考试时长"
              size="small"
            ></el-input>
          </v-input>
          <v-input sm="24" label="校验题">
            <el-radio v-model="taskObj.authentication" :label="false">不显示</el-radio>
            <el-radio v-model="taskObj.authentication" :label="true">显示</el-radio>
          </v-input>
          <v-input sm="24" label="成绩显示">
            <el-radio v-model="taskObj.scoreShow" :label="false">不显示</el-radio>
            <el-radio v-model="taskObj.scoreShow" :label="true">显示</el-radio>
          </v-input>
          <v-input sm="24" label="试卷数量">
            <el-input
              type="number"
              min="1"
              :disabled="mode == 'edit'"
              v-model.number="taskObj.amount"
              placeholder="参与人数"
              size="small"
            ></el-input>
          </v-input>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">关闭</el-button>
          <el-button
            size="small"
            type="danger"
            @click="mode == 'add' ? addTask() : editTask()"
          >{{mode == "add" ? "新增任务" : "更新任务"}}</el-button>
        </div>
      </el-dialog>
    </div>
    <div v-else>
      <div class="module-detail-header">
        <el-breadcrumb separator-class="el-icon-arrow-right" class="f-left">
          <el-breadcrumb-item @click.native="back" class="cursor-p">考试列表</el-breadcrumb-item>
          <el-breadcrumb-item @click.native="showTask = true">任务列表</el-breadcrumb-item>
          <el-breadcrumb-item>试卷列表</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-input
        size="small"
        placeholder="请输入内容"
        prefix-icon="el-icon-search"
        v-model="username"
        @change="handleSearchPaperChange"
        @keyup.enter.native="getPaperByName()"
        style="margin-left: 10px; width: 24%; margin-bottom: 10px;"
      ></el-input>
      <el-button type="plain" circle icon="el-icon-refresh"  @click="handlePaperAnswerNum()"></el-button>
      <el-row :gutter="12">
        <el-col :span="8" v-for="(item,index) in paperList" :key="index">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span v-if="!item.user">试卷{{(searchObj.page-1)*searchObj.size+index+1}}</span>
              <span class="text-danger" v-if="!item.user">(未作答)</span>
              <span v-else>
                <span class="text-danger">
                  {{item.user.name}}-
                  <span v-if="item.user.company">{{item.user.company.name}}</span>
                  -{{item.user.project}}
                </span>
                <span class="text-success">总分:{{item.score}}</span>
              </span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click="getPaperDetail(item)"
              >查看试卷</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="p-t-10" v-if="pageCount>1">
        <el-col :span="10" :offset="14">
          <el-pagination
            class="f-right"
            @current-change="handleCurrentChange"
            :current-page.sync="searchObj.page"
            :page-size="searchObj.size"
            :page-count="pageCount"
            background
            layout="prev, pager, next"
          ></el-pagination>
        </el-col>
      </el-row>
      <el-dialog width="60%" :visible.sync="dialogVisible1">
        <div slot="title" class="dialog-title">
          <span class="text-danger" v-if="!paperObj.user">(未作答)</span>
          <span v-else>
            <span class="text-danger">
              {{paperObj.user.name}}-
              <span
                v-if="paperObj.user.company"
              >{{paperObj.user.company.name}}</span>
              -{{paperObj.user.project}}
            </span>
            <span class="text-success">总分:{{paperObj.score}}</span>
          </span>
        </div>
        <div class="over-hid">
          <div class="question-list" v-for="(item,index) in questionList">
            <div class="question-type">
              试题{{index+1}}:
              <span class="bold">{{formatType(item.question.type)}}</span>
              <!-- <span v-if="item.score == 0" class="text-danger">（回答错误）</span> -->
            </div>
            <div class="question-title">
              <span class="bold">{{item.question.body.title}}</span>
            </div>
            <div class="options" v-if="item.question.type < 3">
              <div
                class="opt-list"
                v-for="(item1,index1) in item.question.options"
              >{{formatOpt(index1)}}{{item1}}</div>
            </div>
            <div class="answer" v-if="paperObj.user">
              考生选择：
              <span
                :class="item.score > 0 ? 'text-success' : 'text-danger'"
              >{{item.answer ? formatVal(item.answer) : "未作答"}}&nbsp;&nbsp;</span> 正确答案：
              <span
                class="text-success"
              >{{item.question.answer ? formatVal(item.question.answer) : "未设置正确答案"}}</span>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisible1 = false">关闭</el-button>
        </div>
      </el-dialog>

      <el-dialog width="60%" :visible.sync="dialogVisible2">
        <div id="app">
          <span>ss</span>
          <el-progress
            v-for="(item,index) in paperAnalyze"
            :key="index"
            :text-inside="true"
            :stroke-width="26"
            :percentage="item.scorePercent"
            status="success"
            style=" margin: 10px;
            width: 500px; margin-left: 150px;"
          ></el-progress>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisible2 = false">关闭</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { userService } from "api";
import { taskOpts } from "./task";
import { vInput } from "vHome";
import paperList from "./paperList";
export default {
  props: ["data", "index"],
  components: {
    vInput,
    paperList
  },
  data() {
    return {
      taskList: [],
      taskOpts,
      pageCount: 1,
      taskObj: {},
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      mode: "add",
      refreshList: 0,
      taskId: "",
      showTask: true,
      paperList: [],
      searchObj: {
        page: 1,
        size: 10
      },
      refreshList1: 0,
      questionList: [],
      paperAnalyze: [],
      qrcodeSrc: "",
      scoreCodeSrc: "",
      paperObj: {},
      refreshList2: 0,
      username: "",
      nameSearchObj: {
        page: 1,
        size: 10
      }
    };
  },
  methods: {
    formatVal(val) {
      return val.replace(
        /0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|false|true/g,
        function(val) {
          switch (val) {
            case "0":
              return "A";
              break;
            case "1":
              return "B";
              break;
            case "2":
              return "C";
              break;
            case "3":
              return "D";
              break;
            case "4":
              return "E";
              break;
            case "5":
              return "F";
              break;
            case "6":
              return "G";
              break;
            case 7:
              return "H ";
              break;
            case 8:
              return "I ";
              break;
            case 9:
              return "J ";
              break;
            case 10:
              return "K ";
              break;
            case 11:
              return "L ";
              break;
            case 12:
              return "M ";
              break;
            case 13:
              return "N ";
              break;
            case 14:
              return "O ";
              break;
            case "false":
              return "错误";
              break;
            case "true":
              return "正确";
              break;
          }
        }
      );
    },
    formatOpt(index) {
      switch (index) {
        case 0:
          return "A ";
          break;
        case 1:
          return "B ";
          break;
        case 2:
          return "C ";
          break;
        case 3:
          return "D ";
          break;
        case 4:
          return "E ";
          break;
        case 5:
          return "F ";
          break;
        case 6:
          return "G ";
          break;
        case 7:
          return "H ";
          break;
        case 8:
          return "I ";
          break;
        case 9:
          return "J ";
          break;
        case 10:
          return "K ";
          break;
        case 11:
          return "L ";
          break;
        case 12:
          return "M ";
          break;
        case 13:
          return "N ";
          break;
        case 14:
          return "O ";
          break;
      }
    },
    formatType(type) {
      switch (type) {
        case 1:
          return "单选题";
          break;
        case 2:
          return "多选题";
          break;
        case 3:
          return "判断题";
          break;
      }
    },
    handleCurrentChange() {
      this.refreshList1++;
    },
    formatNum(num) {
      console.log(num);
    },
    strToDate(dateStr) {
      dateStr = dateStr.replace(/\-/g, "/");
      return new Date(dateStr);
    },
    getPaperDetail(item) {
      let id = item.id;
      this.paperObj = item;
      this.dialogVisible1 = true;
      let obj = {
        page: 0,
        size: 200
      };
      userService.getPaperDetail(id, obj).then(res => {
        let questionList = res.content;
        questionList.forEach(item => {
          item.question.body = JSON.parse(item.question.body);
        });
        this.questionList = questionList;
      });
    },
    getPaperAnalyze(item) {
      let id = item.id;
      this.paperObj = item;
      this.dialogVisible2 = true;
      userService.getPaperAnalyze(id).then(res => {
        this.paperAnalyze = res;
      });
    },
    getPaperList() {
      let obj = {
        page: this.searchObj.page - 1,
        size: this.searchObj.size,
        sort: "id",
        "id.dir": "desc"
      };
      userService.getPaperList(this.taskId, obj).then(res => {
        this.paperList = res.content;
        this.pageCount = res.totalPages;
      });
    },
    back() {
      this.$emit("update:index", 1);
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.taskObj = row;
      this.mode = "edit";
    },
    handlePaper(row) {
      this.taskId = row.id;
      this.showTask = false;
      this.getPaperList();
    },
    handleQrcode(row) {
      userService.getQrcode(this.data.id, row.id).then(res => {
        this.qrcodeSrc = res.url;
      });
    },
    handleScoreCode(row) {
      userService.getScorecode(this.data.id, row.id).then(res => {
        this.scoreCodeSrc = res.url;
      });
    },
    handlePaperAnswerNum() {
      let task = this.taskId;
      userService.upPaperAnswerNum(task).then(res => {
      console.log("刷新试卷个数"+res);
       this.$notify({
          message: "刷新试卷成功！",
          type: "success"
        });
      });
    },
    openDialog() {
      this.dialogVisible = true;
      this.taskObj = {};
      this.mode = "add";
    },
    addTask() {
      if (!this.taskObj.title)
        return this.$notify({
          message: "请填写任务名称",
          type: "warning"
        });
      if (!this.taskObj.amount || this.taskObj.amount <= 0)
        return this.$notify({
          message: "试卷数量错误！",
          type: "warning"
        });

      if (!this.taskObj.begin)
        return this.$notify({
          message: "请选择开始时间",
          type: "warning"
        });
      if (!this.taskObj.end)
        return this.$notify({
          message: "请选择结束时间",
          type: "warning"
        });
      let startTime = this.strToDate(this.taskObj.begin).getTime();
      let endTime = this.strToDate(this.taskObj.end).getTime();
      let num = ((endTime - startTime) / 1000 / 60).toFixed(2);
      this.taskObj.duration = Math.floor(this.taskObj.duration);
      if (
        !this.taskObj.duration ||
        this.taskObj.duration <= 0 ||
        this.taskObj.duration > num
      )
        return this.$notify({
          message: "考试时长错误！",
          type: "warning"
        });
      this.taskObj.deltask = true;
      userService.addTask(this.data.id, this.taskObj).then(res => {
        debugger;
        this.dialogVisible = false;
        console.log(this.refreshList);
        this.refreshList++;
        console.log(this.refreshList);
        this.$notify({
          message: "添加成功！",
          type: "success"
        });
      });
    },
    openDel(row) {
      this.$confirm("此操作将删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.taskId = row.id;
          row.delTask = false;
          userService.delDisTask(this.taskId, row.delTask).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.dialogVisible = false;
            this.refreshList++;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    editTask() {
      if (!this.taskObj.title)
        return this.$notify({
          message: "请填写任务名称",
          type: "warning"
        });
      if (!this.taskObj.begin)
        return this.$notify({
          message: "请选择开始时间",
          type: "warning"
        });
      if (!this.taskObj.end)
        return this.$notify({
          message: "请选择结束时间",
          type: "warning"
        });
      let startTime = this.strToDate(this.taskObj.begin).getTime();
      let endTime = this.strToDate(this.taskObj.end).getTime();
      let num = ((endTime - startTime) / 1000 / 60).toFixed(2);
      this.taskObj.duration = Math.floor(this.taskObj.duration);
      if (
        !this.taskObj.duration ||
        this.taskObj.duration <= 0 ||
        this.taskObj.duration > num
      )
        return this.$notify({
          message: "考试时长错误！",
          type: "warning"
        });
      userService.editTask(this.taskObj.id, this.taskObj).then(res => {
        this.dialogVisible = false;
        this.refreshList++;
        this.$notify({
          message: "编辑成功！",
          type: "success"
        });
      });
    },
    getTaskList() {
      userService.getTaskList(this.data.id).then(res => {
        let taskLs = [];
        for (let index = 0; index < res.content.length; index++) {
          if (res.content[index].deltask == true) {
            taskLs.push(res.content[index]);
          }
        }
        this.taskList = taskLs;
      });
    },
    handleCurrentChange() {
      if (this.username) {
        console.log(this.username);
        this.nameSearchObj.page = this.searchObj.page;
        this.nameSearchObj.size = this.searchObj.size;
        this.refreshList2++;
      } else {
        this.refreshList1++;
      }
    },
    handleSearchPaperChange(value) {
      console.log("value" + value);
      this.searchObj.page = 1;
      if (value.length == 0) {
        this.username = "";
        return this.refreshList1++;
      } else {
        this.paperList.page = 1;
        this.username = value;
        console.log("this." + this);
        return this.refreshList2++;
      }
    },
    getPaperByName() {
      debugger;
      let obj = {
        page: this.nameSearchObj.page - 1,
        size: this.nameSearchObj.size
      };
      console.log("nihao" + obj);
      let task = this.taskId;
      let name = this.username;
      console.log("taskname" + task + name);
      userService.getPaperByName(task, name, obj).then(res => {
        debugger;
        if (res == null) {
          console.log("返回结果失败");
        }
        this.paperList = res.content;
        this.pageCount = res.totalPages;
        console.log("this" + this);
      });
    }
  },
  mounted() {
    this.refreshList++;
  },
  watch: {
    refreshList: "getTaskList",
    refreshList1: "getPaperList",
    refreshList2: "getPaperByName"
    // "taskObj.amount"(newVal){
    //  this.taskObj.amount = Math.abs(this.taskObj.amount)
    //  // return parseInt(newVal)
    //  console.log(newVal)
    //  if(newVal<1){

    //  }
    // }
  }
};
</script>
<style scoped>
.clearfix {
  font-size: 14px;
}

.box-card {
  margin-bottom: 12px;
}

.qrcode {
}

.question-list {
  margin-bottom: 10px;
}

.paper-inf {
  position: absolute;
}
</style>
